import cloud from 'wx-server-sdk';
cloud.init({
  env: 'sleep-sign-0g9xr6lm95e07431',
});
const db = cloud.database()
const user_chaoxing = db.collection('user_chaoxing')
async function getConfigByUsername(username: string): Promise<DBSingleResult<UserChaoxing>> {
  // 没有记录,会抛出异常
  return user_chaoxing.doc(username).get() as unknown as Promise<DBSingleResult<UserChaoxing>>
}

async function getConfigAll(): Promise<DBResult<UserChaoxing>> {
  // 没有记录,会抛出异常
  return user_chaoxing.where({}).get() as unknown as Promise<DBResult<UserChaoxing>>
}

async function setOrUpdateConfigByUsername(data: UserChaoxing) {
  try {
      await getConfigByUsername(data._id);
    // 数据库中存在
    const { _id, ..._data } = data;
    user_chaoxing.doc(data._id).update({ data: _data })
  } catch (ignored) {
    // 数据库中不存在 直接抛出异常
    user_chaoxing.add({ data, })
  }
}


export default { getConfigByUsername, setOrUpdateConfigByUsername, getConfigAll }
